package com.example.as_sum.util;

import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.widget.Toast;

import com.example.as_sum.R;
import com.example.as_sum.application.AppApplication;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.Callback;
import com.zhy.http.okhttp.https.HttpsUtils;
import com.zhy.http.okhttp.log.LoggerInterceptor;

import org.apache.http.conn.ssl.SSLSocketFactory;

import java.io.File;
import java.io.InputStream;
import java.util.Map;
import java.util.concurrent.TimeUnit;


import okhttp3.Cache;
import okhttp3.Call;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Response;
/**
 * Created by ran on 2016/7/19.
 */
public class OkHttpUtil {
    private static final long CACHE_SIZE = 1024 * 1024 * 50;
    /**
     * 单例模式
     */
    private static OkHttpClient mOkHttpClient = null;
    public static OkHttpClient getInstance() {
        if (mOkHttpClient == null) {
            synchronized (OkHttpClient.class) {
                if (mOkHttpClient == null) {
                    mOkHttpClient= init();
                }
            }
        }
        return mOkHttpClient;
    }
    public OkHttpClient getOkHttpClient(){
        if(mOkHttpClient!=null){
            return mOkHttpClient;
        }else{
            return init();
        }
    }

    /**
     * 初始化OkHttpClient对象
     * @return
     */
    private static OkHttpClient init() {
        //信任证书
        InputStream trustManager = AppApplication.aContext.getResources().openRawResource(
                R.raw.cib);
        //信任证书列表
        InputStream [] trustManagers=new InputStream[]{trustManager};

        //客户端证书
        InputStream keyManagers = AppApplication.aContext.getResources().openRawResource(
                R.raw.my);
        //HttpsUtils.SSLParams sslParams = HttpsUtils.getSslSocketFactory(trustManagers, keyManagers, "3601479");
       HttpsUtils.SSLParams sslParams = HttpsUtils.getSslSocketFactory(null, null, null);

        File cacheFile = new File(AppApplication.aContext.getCacheDir(), "github_repo");
        Cache cache = new Cache(cacheFile, CACHE_SIZE);

        OkHttpClient client = new OkHttpClient.Builder()
                .cache(cache)
                .connectTimeout(10000L, TimeUnit.MILLISECONDS)
                .readTimeout(10000L, TimeUnit.MILLISECONDS)
                .addInterceptor(new LoggerInterceptor("TAG"))//拦截器，可以自定义
                .hostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER)//域名验证
                .sslSocketFactory(sslParams.sSLSocketFactory, sslParams.trustManager)
                .build();
        OkHttpUtils.initClient(client);
        return client;
    }
    public static void get(final Handler handler, String url,
                            Map<String,String> param, final int... type) {
        if(param == null){
            OkHttpUtils.get()
                    .url(url)
                    .build()
                    .execute(new MyCallback(handler,type[0]));
        }else{
             OkHttpUtils.get()
                        .url(url)
                        .params(param)
                        .build()
                        .execute(new MyCallback(handler,type[0]));
        }
    }
    public static void post(final Handler handler, final String url,
                            Map<String,String> param, final int... type) {
        if(param == null){
            OkHttpUtils.post()
                    .url(url)
                    .build()
                    .execute(new MyCallback(handler, type[0]));
        }else {
            OkHttpUtils.post()
                    .url(url)
                    .params(param)
                    .build()
                    .execute(new MyCallback(handler, type[0]));
        }
    }
    public static void post(final Handler handler, final String url,
                            final String content, final int... type) {
        OkHttpUtils.postString()
                .url(url)
                .mediaType(MediaType.parse("application/json; charset=utf-8"))
                .content(content)
                .build()
                .execute(new MyCallback(handler,type[0]));
    }
    static class MyCallback extends Callback{
        private Handler handler;
        private final int type;
        public MyCallback(Handler handler,int type){
            this.handler=handler;
            this.type=type;
        }
        @Override
        public Object parseNetworkResponse(Response response, int id) throws Exception {
            int code= response.code();//返回的状态码
            Message message=Message.obtain();
            //200 <= code < 300是成功
            if(response.isSuccessful()){
                //返回成功
                message.what=type;
                message.obj=response.body().string();
                handler.sendMessageDelayed(message, 2000);
            }else{
                //返回失败
                message.what=0;
                message.arg1=type;
                message.arg2=2003;
                handler.sendMessageDelayed(message, 2000);
            }
            return null;
        }

        @Override
        public void onError(Call call, Exception e, int id) {
            Bundle bundle = new Bundle();
            Message message=Message.obtain();
            bundle.putString("error","服务器未响应啊啊啊啊");
            message.setData(bundle);

            message.what=0;
            message.arg1=type;
            message.arg2=1003;
            handler.sendMessageDelayed(message,2000);
        }

        @Override
        public void onResponse(Object response, int id) {

        }
    }
}
